
/*
 * 수정 이력 : 2011-10-18 (최병옥) 
 * */
package attend.action.login;

import org.apache.log4j.Logger;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsStatics;
import org.apache.struts2.interceptor.ServletResponseAware;

import attend.UserContainer.User;
import attend.com.CodeMetrix;
import attend.dao.BDADM.BDADM_AuthDAO;
import attend.dao.login.LoginDao;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import exception.BaseException;

/**
 * @author Administrator
 *
 */
public class LoginAction extends ActionSupport implements ServletResponseAware {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(LoginAction.class);
	
	private static final long serialVersionUID = 1L;
	
	private HashMap<String, String>						empInfo 	= null;	//사원정보
	private HashMap<String , HashMap<String, String>>	authMenu 	= null;	//

	private HashMap<String, String>[]			menu 	= null;		// 소메뉴를 담아 화면에 전달 하기 위해 생성
	private HashMap<String, String>[]			main_menu 	= null;	// 대메뉴를 담아 화면에 전달 하기 위해 생성
		
	private List<HashMap<String, String>>	listMenu 	= null;	//Accessible Menu
	

	private String 				msg;
	private String 				user_id;
	private String 				pass;
	private User				user;
	private String 				sessionTime;
	
	private Map 				session;
	
	private LoginDao 			loginDao;
	private BDADM_AuthDAO		authDao;		//메뉴접근권한 DAO

	private int 				emp_no;
	
	private	String				current_pwd;	//현재 비번
	private	String				new_pwd_1;		//변경할 비번
	private	String				new_pwd_2;		//변경할 비번 확인
	
	private	String[] menu_access_yn 	= null;	//메뉴 접근 권한
	private	String[] menu_code 			= null;	//메뉴코드
	private	String[] menu_url 			= null;	//URI
	
	private HttpServletResponse response;
	
	public LoginAction() {
	}

	/* (non-Javadoc)
	 * @see com.opensymphony.xwork2.ActionSupport#execute()
	 */
	public String execute() throws BaseException , SQLException {
		
		user = new User();
		
		 ActionContext context = ActionContext.getContext();
         HttpServletRequest request = (HttpServletRequest)context.get(StrutsStatics.HTTP_REQUEST);
         
         logger.info(request.getRemoteAddr());
         
         
         logger.info(request.getRemoteHost());
         logger.info(request.getRemoteUser());
         logger.info(request.getRemotePort());
         logger.info(request.getPathTranslated());
         
         logger.info(request.getLocalAddr());

		
		System.out.println("LoginAction~~~~~~~~~~~~~~~~~~~~~~~~~~~~START          " + request.getRemoteAddr() + "  "+ new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
		
    	loginDao 				= 	new LoginDao();

//    	Cookie[] cookie ; 
//    		
//    	cookie =	ServletActionContext.getRequest().getCookies();
    	
//    	if (cookie == null) {
//			cookie = new Cookie[0];
//		}
//    	
//    	for (int i = 0; i < cookie.length; i++) {
			
//    		System.out.println(i + " Cookie Name --->   " + cookie[i].getName());
//			System.out.println(i + " Cookie Value --->   " + cookie[i].getValue());
//			System.out.println(i + " Cookie MaxAge --->   " + cookie[i].getMaxAge());
//			System.out.println(i + " Cookie Domain --->   " + cookie[i].getDomain());
//			System.out.println(i + " Cookie Domain --->   " + cookie[i].getDomain());
//			System.out.println(i + " Cookie Path --->   " + cookie[i].getPath());
			
//			if (cookie[i].getName().equals("user_id")) {
//				if (user_id == null || user_id.equals("")) {
//					user_id = cookie[i].getValue();
//					cookie[i].setMaxAge(0);
//				} else {
//					cookie[i].setValue(user_id);
//				}
//				
//			}
//		}
    	
    	//ServletActionContext.getResponse().addCookie(cookie[0]);
    	
    	if (user_id == null || pass == null || user_id.trim().equals("") || pass.trim().equals("")) {
    		
			return LOGIN;
		}
    	
    	Cookie ck = new Cookie("user_id" , user_id );
    	ck.setDomain("*.philsys.co.kr");
//    	ck.setDomain(getText("cookie.domain"));
    	ck.setMaxAge(3600 * 24 * 7);
    	
    	response.setHeader("P3P","CP='CAO PSA CONi OTR OUR DEM ONL'");
		response.addCookie(ck);
    	
    	loginDao.retrieveEmp(user_id , pass);
    	
    	setMsg(loginDao.getMsg());
    	
    	empInfo = loginDao.getEmpInfo();
    	
    	//로그인 페이지로 이동
    	if (empInfo == null ||empInfo.size() < 1) {
    		return LOGIN;
    	}
    	//메뉴권한여부를 모두 조회한다.
    	
    	// 대 메뉴를 담음
    	loginDao.retrieveAuthMenuList(Integer.valueOf(empInfo.get("emp_no"))); // 사용자가 볼수 있는 대메뉴 목록 select
    	listMenu = loginDao.getList();    	
    	
    	// 받아온 대메뉴 list를 화면에 넘기기 위해 HashMap 형태로 변환
    	main_menu = new HashMap[listMenu.size()];
    	for (int i = 0; i<listMenu.size(); i++){
    		main_menu[i] = listMenu.get(i);    		
    	}
    	
    	//user.setAuth_menu(mainMenu);
    	
    	authDao		=	new BDADM_AuthDAO();
    	
    	// 소메뉴를 DB에서 받아온다.
    	authDao.searchMenu2(empInfo.get("position_no"));	//직위
    	listMenu	=	authDao.getList();
    	
    	// 받아온 소메뉴 list를 화면에 넘기기 위해 HashMap 형태로 변환
    	menu	=	new HashMap[listMenu.size()];
    	for (int i = 0; i < listMenu.size(); i++) {
    		menu[i]	=	listMenu.get(i);
    		
    		//System.out.println(menu[i]);
		}
    	
		user.setUser_id(user_id);
		user.setEmpInfo(empInfo);
    	
    	//사원정보를 담아 온다.
    	sessionTime = loginDao.createSession();
		System.out.println("sessionTime--------------------===>				" + sessionTime);
		
		if(sessionTime == null) return "sessionfail";
			
		///////////////////////////////////////////////////////////////////////////
		///////////////////////////////////////////////////////////////////////////
		session = ActionContext.getContext().getSession();
		
		//user 객체에 유저권한 등을 추가해서 관리하면 된다.
		session.put("user", user);
		//session.put("empInfo", empInfo);
		
		session.put("main_menu", main_menu); 	// 대메뉴 목록
		session.put("menu", menu); 				// 소메뉴 목록
		
		
		//관리자 아이디일 경우 action을 관리자 페이지로 넘긴다.
		if (user.getUser_id().toUpperCase().equals(CodeMetrix.ADMIN)) {
			return "admin";
		}

		return SUCCESS;
	}

	/**
	 * <pre>
	 * 로그인
	 * </pre>
	 */
	public String loginTry() throws BaseException {
		
		user = new User();
		
		loginDao	=	new LoginDao();
		
		loginDao.retrieveEmp(user_id , pass);
		
		setMsg(loginDao.getMsg());
//		System.out.println(msg + "@@@@@@@@@@@       msg..........  ");
		
		empInfo		=	loginDao.getEmpInfo();
		
		System.out.println("------------------------------------------------------------------------");
		System.out.println("사원개인정보");
		System.out.println(empInfo);
		System.out.println("------------------------------------------------------------------------");
		
		
		//사용자정보가 없을시 로그인 페이지로 이동한다. 
		if (empInfo == null) {
			msg	=	"사용자 정보가 없습니다.";
			return LOGIN;
		}
		
		//메뉴권한여부를 모두 조회한다.
    	loginDao.retrieveAuthMenuList(Integer.valueOf(empInfo.get("emp_no")));
    	user.setAuth_menu(authMenu);	//널포인터 발생시 객체생성이 되었는지 확인한다.
		
		//어드민 비교
		if (user.getUser_id().toUpperCase().equals(CodeMetrix.ADMIN)) {
			return "admin";
		}
		
		//세션을 얻는다.
//		session	=	ActionContext.getContext().getSession();
//		session.put("empinfo", empInfo);
		
		return SUCCESS;
	}
	
	/**
	 * <pre>
	 * 로그아웃
	 * session 제거
	 * </pre>
	 * @return
	 * @throws BaseException
	 * @since	2009/02/10
	 */
	public String logout() throws BaseException {
		//세션을 얻는다.
		session	=	ActionContext.getContext().getSession();
		
		user = (User)session.get("user");
		
//		user_id = user.getUser_id();
		
		user 	= null;
		menu	=	null;
		
		session.remove("user");
		session.remove("menu");
		session.clear();
		
		session	=	null;
		
		ActionContext.getContext().setSession(null);
		
		
		return SUCCESS;
	}
	
	/**
	 * <pre>
	 * session에 empInfo이 있다면 true 
	 * 아니면 false
	 * </pre>
	 * @return
	 */
	public boolean hasSession() {

		return session.containsKey("user");
		
	}
	
	/**
	 * <pre>비밀 번호 변경</pre>
	 * @return
	 * @throws BaseException
	 */
	public String passwordChange() throws BaseException {
		
		//세션에서 정보를 가져다가 설정한다.
		session = 	ActionContext.getContext().getSession();
		
		if (session.isEmpty() || session.get("user") == null ) {
			return "sessionfail";
		}
		
		user 	=	(User)session.get("user");
		//empInfo	=	(HashMap<String, String>) session.get("empInfo");
		empInfo	=	user.getEmpInfo();
		menu	=	(HashMap<String, String>[]) session.get("menu");
		setUser_id(user.getUser_id());
		
		//사번 설정
		emp_no = Integer.valueOf(empInfo.get("emp_no"));
		
		
		return SUCCESS;
	}
	
	/**
	 * <pre>비밀번호 수정</pre>
	 * @return
	 * @throws BaseException
	 * @since 2009/03/05
	 */
	public String updatePassword() throws BaseException {
		
		loginDao	=	new		LoginDao();
		
		loginDao.updatePassword(emp_no , user_id , current_pwd , new_pwd_1);
		setMsg(loginDao.getMsg());
		
		/*
		 * if (msg.equals(CodeMetrix.OK)) {
			setMsg(getText("alert.message.ok"));
		} else if (msg.equals(CodeMetrix.FAILE)) {
			setMsg(getText("alert.message.fail"));
		} else if (msg.equals(CodeMetrix.NOTEXIST)) {
			setMsg(getText("alert.message.no"));
		}
		*/
		
		return SUCCESS;
	}
	
	/**
	 * 달력 테스트
	 * @return
	 * @throws BaseException
	 */
	public String cal() throws BaseException {
		
		return SUCCESS;
	}
	
	/******************************************************************************************/
	public String getUser_id() {
		return user_id;
	}
	
	public void setUser_id(String user_id) {
		this.user_id = user_id;
	}
	
	public String getPass() {
		return pass;
	}
	
	public void setPass(String pass) {
		this.pass = pass;
	}

	public HashMap<String, String> getEmpInfo() {
		return empInfo;
	}

	public void setEmpInfo(HashMap<String, String> empInfo) {
		this.empInfo = empInfo;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public User getUser() {
		return user;
	}
	
	public String doReturn() throws Exception {
		return SUCCESS;
	}
	
	public String getSessionTime() {
		return sessionTime;
	}

	public void setSessionTime(String sessionTime) {
		this.sessionTime = sessionTime;
	}

	public int getEmp_no() {
		return emp_no;
	}

	public void setEmp_no(int emp_no) {
		this.emp_no = emp_no;
	}

	public String getCurrent_pwd() {
		return current_pwd;
	}

	public void setCurrent_pwd(String current_pwd) {
		this.current_pwd = current_pwd;
	}

	public String getNew_pwd_1() {
		return new_pwd_1;
	}

	public void setNew_pwd_1(String new_pwd_1) {
		this.new_pwd_1 = new_pwd_1;
	}

	public String getNew_pwd_2() {
		return new_pwd_2;
	}

	public void setNew_pwd_2(String new_pwd_2) {
		this.new_pwd_2 = new_pwd_2;
	}

	public List<HashMap<String, String>> getListMenu() {
		return listMenu;
	}

	public void setListMenu(List<HashMap<String, String>> listMenu) {
		this.listMenu = listMenu;
	}

	public String[] getMenu_access_yn() {
		return menu_access_yn;
	}

	public void setMenu_access_yn(String[] menu_access_yn) {
		this.menu_access_yn = menu_access_yn;
	}

	public String[] getMenu_code() {
		return menu_code;
	}

	public void setMenu_code(String[] menu_code) {
		this.menu_code = menu_code;
	}

	public String[] getMenu_url() {
		return menu_url;
	}

	public void setMenu_url(String[] menu_url) {
		this.menu_url = menu_url;
	}

	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	/**
	 * @return the response
	 */
	public HttpServletResponse getResponse() {
		return response;
	}

	/**
	 * @param response the response to set
	 */
	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}


	/******************************************************************************************/

}
